package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.framework.entity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.service.IEmpService;
import com.ldk.framework.service.IHelpDocService;
import com.ldk.framework.service.IPlatformService;

@Controller
@RequestMapping("/emp")
public class EmpController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "emp";
    /**
     * 模块名称
     */
    private final String module = "员工";

    @Autowired
    private IEmpService empService;
    @Autowired
    private IPlatformService platformService;

    @RequestMapping("/list")
    public ModelAndView list(ModelMap map,HttpServletRequest request,
                             HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        setLinks(map, "", "", module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add");
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        return new ModelAndView("/emp/list");
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<Emp> getList(@RequestParam(value="page",required=false,defaultValue="1") int page,
                                             @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
                                             @RequestParam(value="name",required=false,defaultValue="") String name,
                                             HttpServletRequest request)
    {
        int limit = pageSize;
        int offset = (page -1) * pageSize;

        Emp query = new Emp();
        if(!StringUtils.isBlank(name)){
            query.setName(name);
        }

        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Emp> result = empService.selectPageList("", query, pageable);

        LigerUIGridResult<Emp> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @RequestMapping("/add")
    public ModelAndView add(ModelMap map,HttpServletRequest request,
                            HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);

        setLinks(map, module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
        setForm(map, "/"+route+"/insert", null);
        map.addAttribute("module", module);
        //map.addAttribute("platforms", getPlatforms());

        Emp model = new Emp();

        return new ModelAndView("/emp/info","model",model);
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map,HttpServletRequest request,
                             HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        Emp query = new Emp();
        query.setId(id);

        Emp model = empService.selectByKey("", query);
        if(model == null){
            return new ModelAndView("redirect:/"+route+"/list");
        }
        setLinks(map, module+"管理", "/"+route+"/list", "编辑"+module, "/"+route+"/edit/"+id, "", "");
        setForm(map, "/"+route+"/update", null);
        map.addAttribute("module", module);
        //map.addAttribute("platforms", getPlatforms());

        return new ModelAndView("/emp/info","model", model);
    }

    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") Emp model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);

        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try{

            Emp query = new Emp();
            query.setName(model.getName());

            long count = empService.selectCount("", query);
            if(count > 0){
                rst.AddError(String.format(" 员工:%s已经存在", model.getName()));

                return new ModelAndView("redirect:/"+route+"/add");
            }

            //操作日志
            this.insertOplog(request,module,"","","添加:"+model.getName(),this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = empService.insert("",model);
            if(row > 0){
                rst.AddOk("添加"+module+"成功");
            }
            else{
                rst.AddError("添加"+module+"失败");
            }
        }
        catch(Exception e){
            rst.AddError("添加"+module+"失败");
            logger.error(e.getMessage());
        }
        return new ModelAndView("redirect:/"+route+"/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") Emp model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response)
    {
        //session是否过期
        this.isExpired(request,response);

        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try{
            Emp query = new Emp();
            query.setName(model.getName());

            Emp emp = empService.selectOne("", query);
            if(emp != null && !emp.getName().equals(model.getName())){
                rst.AddError(String.format("员工:%s已经存在", model.getName()));

                return new ModelAndView("redirect:/"+route+"/edit/{id}");
            }
            //操作日志
            this.insertOplog(request,module,"","","修改:"+model.getName(),this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = empService.updateByKey("", model);
            if(row > 0){
                rst.AddOk("修改"+module+"成功");
            }
            else{
                rst.AddError("修改"+module+"失败");
            }
        }
        catch(Exception e){
            rst.AddError("修改"+module+"失败");
            logger.error(e.getMessage());
        }
        return new ModelAndView("redirect:/"+route+"/edit/{id}");
    }

    /**
     * 浏览
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map,HttpServletRequest request,
                             HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        setViewMode(map, ViewMode.View);
        Emp query = new Emp();
        query.setId(id);
        Emp model = empService.selectByKey("", query);

        map.addAttribute("typeList", getDictdataList(3));
        map.addAttribute("module", module);
        map.addAttribute("platforms", getPlatforms());

        return new ModelAndView("/emp/info","model", model);
    }

    @ResponseBody
    @RequestMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request,
                                 HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        ResponseResult rst = new ResponseResult();
        if(id < 1)
        {
            rst.AddError("删除"+module+"错误");
            return rst;
        }
        Boolean successed = false;
        try{
            Emp query = new Emp();
            query.setId(id);

            //操作日志
            Emp appurl = empService.selectByKey("", query);
            this.insertOplog(request,module,"","","设置角色:"+appurl.getName(),this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = empService.deleteByKey("", query);
            successed = row > 0;
        }
        catch(Exception e){
            logger.error(e.getMessage());
        }
        if(successed){
            rst.AddOk("删除"+module+"成功");
        }
        else{
            rst.AddError("删除"+module+"失败");
        }

        return rst;
    }

    /**
     * 获取系统平台
     * @return
     */
    private List<Platform> getPlatforms(){
        Platform query = new Platform();
        query.setEnabled(true);

        List<Platform> platforms = platformService.selectList("", query);

        return platforms;
    }
}
